// pages/index/index.js

import {
  postrequset,
  getrequset
} from "../../utils/request/index"
let timeId = ''; //定时器
const songlist = JSON.parse(wx.getStorageSync('songlist'))
let timeClear = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    targetSeconds: 0, // 目标秒数，可以根据需要动态改变
    currentTime: 0, // 当前已过时间，初始为0
    progress: 0, // 进度百分比，初始为0
    isRunning: false, // 是否正在运行，用于控制播放和暂停
    audioCtx: null,
    istabRunning: false,
    start: "",
    end: "",
    list: '', //歌词
    // src: '',//歌曲地址
    seconds: 0, //当前播放的进度
    scrollTop: 0, //当前歌词下标
    show: false, //弹出层
    showLyric: false,
    index: '',
    option: [],
    song: null,
    value: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.songlist) {
      const songlist = JSON.parse(options.songlist)
      const {
        index
      } = options
      const song = songlist[index]
      const storedState = wx.getStorageSync('musicPlaybackState')
      if (song != null && JSON.parse(storedState.song) != null) {
        if (JSON.parse(storedState.song).song_id !== song.song_id) {
          wx.removeStorageSync({key: 'flag'})
          wx.removeStorageSync("lyricState")
          wx.removeStorageSync("musicPlaybackState")
          wx.removeStorageSync("istabRunning")
        }
      }
      this.setData({
        song,
        index
      })
    } else {
      const storedState = wx.getStorageSync('musicPlaybackState')
      this.setData({
        song: JSON.parse(storedState.song)
      })
    }
    if (this.data.list == '' && this.data.song != {}) {
      wx.request({
        url: this.data.song.song_lyric, // 替换为你的lrc文件的URL
        success: (res) => {
          // 将lrc文件内容存储在data中
          this.setData({
            list: this.formatLrc(res.data)
          })
        }
      });
    }
    this.getsonglist()
  setTimeout(()=>{
    wx.setStorageSync('flag', {"isRunning":true})
    this.togglePlay()
  },1000)


  },
  getsonglist() {
    const user = wx.getStorageSync('user')
    const data = {
      markings: user.user_markings
    }
    getrequset("songlist/list", data).then(res => {
      if (res.code == 200) {
        this.setData({
          option: this.getNewList(res.data.list),
          value: res.data.list[0].playlist_markings
        })
      }

    })
  },
  getNewList(arr) {
    let newarr = arr.map(item => {
      return {
        text: item.playlist_name,
        value: item.playlist_markings
      }
    })

    return newarr;
  },
  //获取当前歌词下标
  songText() {
    let songsList = this.data.list
    let timeSongs = this.data.seconds
    if (songsList.length > 0) {
      for (let i = 0; i < songsList.length - 1; i++) {
        const element = songsList[i];
        const element2 = songsList[i + 1];
        if (timeSongs >= element.time && timeSongs < element2.per) {
          if (timeSongs >= element2.time) {
            this.setData({
              scrollTop: i,
            })
          }
        }
      }
    }
  },
  //把歌词格式化
  formatLrc(list) {
    var strLrc = list.split("\n"); //按换行截取字符串，去掉换行得到一个数组strLrc 
    let arr = [] //声明数组
    for (var i = 0; i < strLrc.length; i++) { //循环strLrc 
      var str = strLrc[i];
      var parts = str.split("]"); //按照']'截取strLrc的每一项，得到新数组parts 
      var timeStr = ''; //获取时间字符串
      if (parts[0].substring(1)) {
        timeStr = this.convertTimeToSeconds(parts[0].substring(1))
      }
      var obj = {
        time: timeStr,
        words: parts[1],
        per: 0
      };

      arr.push(obj) //每循环一次把obj添加到arr数组末尾
    }
    for (let i = 0; i < arr.length - 1; i++) {
      const element = arr[i];
      element.per = arr[i + 1].time
    }
    return arr;
  },
  convertTimeToSeconds(timeStr) {
    // 将时间字符串拆分为小时、分钟和秒
    const [_, hours, minutes, seconds] = timeStr.match(/(\d{2}):(\d{2})\.(\d{3})/);
    // 将小时乘以3600（秒），分钟乘以60（秒）并将其加在一起，以获得总秒数
    if (timeStr) {
      const totalSeconds = parseInt(hours) * 60 + parseInt(minutes) + parseInt(seconds) / 1000;
      return totalSeconds;
    }
  },
  scroll(e) {
    clearInterval(timeId)
    const num = (e.detail.scrollTop / 30) + 6
    this.setData({
      scrollTop: num
    })

    let scrollTime = setInterval(() => {
      if (this.data.scrollTop == num) {
        timeId = setInterval(() => {
          this.songText()
        }, 500)
        clearInterval(scrollTime)
      }
    }, 3000)

  },
  onClicktoggle() {
    this.setData({
      showLyric: !this.data.showLyric
    })
  },
  onPopup() {
    this.setData({
      show: true
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  // 抽象方法：保存播放状态
  savePlaybackState() {
    wx.setStorageSync('musicPlaybackState', {
      song: JSON.stringify(this.data.song),
    });
    wx.setStorageSync('flag', {
      isRunning: this.data.isRunning
    });
    wx.setStorageSync('lyricState', {
      targetSeconds: this.data.targetSeconds,
      currentTime: this.data.currentTime+Number.parseFloat(0.5),
      progress: this.data.progress,
      seconds: this.data.seconds+Number.parseFloat(0.5),
      scrollTop: this.data.scrollTop,
    });
  },
  restorePlaybackState() {
    const storedState = wx.getStorageSync('musicPlaybackState');
    const isRunning = wx.getStorageSync('flag')
    const lyricState = wx.getStorageSync('lyricState')
    if (storedState) {
      // 如果有存储的状态，则恢复
      this.setData({
        targetSeconds: lyricState.targetSeconds,
        isRunning: isRunning.isRunning,
        currentTime: lyricState.currentTime,
        progress: lyricState.progress,
        seconds: lyricState.seconds, //当前播放的进度
        scrollTop: lyricState.scrollTop, //当前歌词下标
        song: JSON.parse(storedState.song) || this.data.song, // 确保默认值或当前数据不被覆盖

      });
      if (lyricState.seconds > 0) {
        this.data.audioCtx.seek(lyricState.seconds);
        // 确保 seek 后再根据状态播放
        setTimeout(() => {
          if (this.data.isRunning) {
            this.onResume();
          }
        }, 100); // 稍作延迟，等待 seek 完成
      } else {
        if (this.data.isRunning) {
          this.onResume();
        }
      }
    }
  },
  initAudio() {
    this.setData({
      audioCtx: wx.createInnerAudioContext(),
    });
    this.data.audioCtx.src = this.data.song.song_path;
    this.data.audioCtx.onTimeUpdate(() => {
      this.updateProgress();
    });
    this.data.audioCtx.onEnded(() => {
      this.onPause();
    });
  },
  togglePlay() {
    if (this.data.isRunning) {
      this.onPause();
    } else {
      this.onResume();
    }
  },
  onResume() {
    this.setData({
      isRunning: true,
    });
    this.data.audioCtx.play();
    this.updateProgress();
  },
  onPause() {
    this.setData({
      isRunning: false,
    });
    this.data.audioCtx.pause();
    this.savePlaybackState()
  },
  updateProgress() {
    const {
      currentTime,
      targetSeconds
    } = this.data;
    const percent = Math.floor((currentTime / targetSeconds) * 100); // 计算进度百分比
    this.setData({
      progress: Math.min(percent, 100)
    }); // 更新进度，确保不超过100%
    if (currentTime < targetSeconds && this.data.isRunning) {
      this.setData({
        currentTime: this.data.audioCtx.currentTime
      })
      setTimeout(() => {
        this.setData({
          currentTime: this.data.audioCtx.currentTime,
          seconds: this.data.audioCtx.currentTime,
        });
        wx.setStorageSync('lyricState', {
          targetSeconds: this.data.targetSeconds,
          currentTime: this.data.currentTime,
          progress: this.data.progress,
          seconds: this.data.seconds, //当前播放的进度
          scrollTop: this.data.scrollTop, //当前歌词下标
        })
      }, 1000); // 每秒更新一次
      wx.setStorageSync('flag', {
        isRunning: this.data.isRunning,
      })
    } else if (currentTime >= targetSeconds) {
      this.onPause(); // 结束时自动暂停
    }
  },
  getTime(num) {
    let m = Math.floor(num / 60);
    let s = Math.floor(num % 60);
    if (s < 10) {
      s = "0" + s;
    }
    let time = m + " : " + s;
    return time
  },
  updateSong(index) {
    const newSong = songlist[index];
    this.setData({
      index,
      song: newSong,
      targetSeconds: Number.parseFloat(newSong.song_duration),
      currentTime: 0,
      progress: 0,
      seconds: 0,
      scrollTop: 0,
    });
    this.savePlaybackState();
    wx.setStorageSync('flag', {
      isRunning: true
    });
    this.data.audioCtx.destroy();
    this.initAudio();
    // 尝试恢复播放状态
    this.restorePlaybackState();

    // 请求歌词等其他操作...
    wx.request({
      url: this.data.song.song_lyric, // 替换为你的lrc文件的URL
      success: (res) => {
        // 将lrc文件内容存储在data中
        this.setData({
          list: this.formatLrc(res.data)
        })
      }
    });
  },
  onClickSwitch(direction) {
    const newIndex = direction === 'left' ?
      (this.data.index === 0 ? songlist.length - 1 : this.data.index - 1) :
      (this.data.index === songlist.length - 1 ? 0 : this.data.index + 1);
    this.updateSong(newIndex);
  },
  onClickLeft() {
    this.onClickSwitch('left');

  },
  onClickRight() {
    this.onClickSwitch('right');
  },
  onClickRemark(){
    wx.navigateTo({
      url: '../remark/index?marking='+this.data.song.song_markings,
     
    
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const i = wx.getStorageSync('index');
    if (i != null || i != "") {
      this.setData({
        index: i
      })
    }
    timeId = setInterval(() => {
      this.songText()
    }, 500)

    this.setData({
      targetSeconds: this.data.song.song_duration
    })


    // 组件挂载时初始化音频上下文
    this.initAudio();
    // 尝试恢复播放状态
    this.restorePlaybackState();


    setInterval(() => {
      if (this.data.isRunning) {
        this.setData({
          start: this.getTime(this.data.audioCtx.currentTime),
          end: this.getTime(this.data.targetSeconds)
        })

      } else {
        this.setData({
          start: this.getTime(this.data.currentTime),
          end: this.getTime(this.data.targetSeconds)
        })
      }
    }, 1000)


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.isRunning) {
      this.onPause();
      wx.setStorageSync('istabRunning', {
        istabRunning: true
      })
      wx.setStorageSync('flag', {
        isRunning: false
      })
    } else {
      this.onPause();
      wx.setStorageSync('istabRunning', {
        istabRunning: false
      })
      wx.setStorageSync('flag', {
        isRunning: false
      })
    }

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})